package com.fjnu.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;


import java.text.SimpleDateFormat;

@Component
@Slf4j
@Aspect
public class DaoAspect {

    @Pointcut("execution(* com.fjnu.dao.*.*(..))")
    public void daoLayer(){

    }

    @Around("daoLayer()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable{
        long start = System.currentTimeMillis();
        String methodName = joinPoint.getSignature().getName();
        String DateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(start);
        Object result = joinPoint.proceed();
        long end = System.currentTimeMillis();
        log.info("[INFO] "+DateTime+" "+methodName+" was executed and spent {} milliseconds. ", end - start);
        return result;
    }

    @Around("@within(com.fjnu.aspect.NPECatch) || @annotation(com.fjnu.aspect.NPECatch)")
    public Object aroundWithNPE(ProceedingJoinPoint joinPoint) throws Throwable{
        try {
            return joinPoint.proceed();
        }catch (Exception e){
            String methodName = joinPoint.getSignature().getName();
            log.info("[ERROR] "+methodName+" was executed and throwed an NPE. ", e);
            return null;
        }
    }
}
